package ru.spb.osll.myfit.server.parser;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import java.util.Vector;

import org.junit.Test;

import ru.spb.osll.myfit.common.PageElement;
import ru.spb.osll.myfit.common.Table;
import ru.spb.osll.myfit.common.TableCell;

public class TableElementParserTest {

  private TableElementParser tableParser = new TableElementParser();

  @Test
  public void testTableWithEmptyCells() {
    String[] tableRows = {"|verify page|", "|Import|",
        "|ru.spb.osll.myfit.fixtures|", "| |", "|create page|",
        "|do something|", "|do this|", "|do this|", "|and that|", "| |"};

    for (String row : tableRows) {
      if (tableParser.matches(row)) {
        tableParser.parse(row);
      }
    }

    PageElement el = tableParser.reset();

    assertNotNull(el);
    assertTrue(el instanceof Table);

    Table table = (Table) el;

    Vector<Vector<TableCell>> rows = table.getData();
    assertEquals(10, rows.size());

    String[] expectedCells = {"verify page", "Import",
        "ru.spb.osll.myfit.fixtures", " ", "create page", "do something",
        "do this", "do this", "and that", " "};
    
    for (int i = 0; i < 10; i++) {
      Vector<TableCell> cells = rows.get(i);
      TableCell realCell = cells.get(0);
      assertEquals(expectedCells[i], realCell.getText());
    }
  }

  @Test
  public void testImportTable() {
    String[] tableRows = {"|Import|", "|ru.spb.osll.myfit.fixtures|"};

    for (String row : tableRows) {
      if (tableParser.matches(row)) {
        tableParser.parse(row);
      }
    }

    PageElement el = tableParser.reset();
    assertNull(el);
  }
  
  @Test
  public void testDoTable(){
    String[] tableRows = {"|Div|", "|dividend|divisor|result?|", "|8|4|2|"}; 
    for (String row : tableRows) {
      if (tableParser.matches(row)) {
        tableParser.parse(row);
      }
    }

    PageElement el = tableParser.reset();

    assertNotNull(el);
    assertTrue(el instanceof Table);

    Table table = (Table) el;

    Vector<Vector<TableCell>> rows = table.getData();
    assertEquals(3, rows.size());

    Vector<TableCell> row0 = rows.get(0);
    Vector<TableCell> row1 = rows.get(1);
    Vector<TableCell> row2 = rows.get(2);
    
    assertEquals(1, row0.size());
    assertEquals(3, row1.size());
    assertEquals(3, row2.size());
    
    String[] expectedRow0 = {"Div"};
    String[] expectedRow1 = {"dividend", "divisor", "result?"};
    String[] expectedRow2 = {"8", "4", "2"};
        
    assertEquals(expectedRow0[0], row0.get(0).getText());
    
    for (int i = 0; i < 3; i++) {
      assertEquals(expectedRow1[i], row1.get(i).getText());
      assertEquals(expectedRow2[i], row2.get(i).getText());
    }
  }
}
